package cn.moon.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

@Slf4j
public class NetworkUtils {

    public static String findFirstNonLoopbackAddress() {
        InetAddress result = null;
        try {

            int lowest = Integer.MAX_VALUE;

            Enumeration<NetworkInterface> nics = NetworkInterface.getNetworkInterfaces();

            while(nics.hasMoreElements()) {
                NetworkInterface ifc = nics.nextElement();
                if (!ifc.isUp()) {
                    continue;
                }

                if (ifc.getIndex() >= lowest && result != null) {
                    continue;
                }

                lowest = ifc.getIndex();

                Enumeration<InetAddress> addrs = ifc.getInetAddresses();
                while(addrs.hasMoreElements()){
                    InetAddress address = addrs.nextElement();
                    if(address instanceof Inet4Address && !address.isLoopbackAddress()){
                        result = address;
                    }
                }

            }
        } catch (IOException e) {
            log.error("获取网卡信息出错", e);
        }

        if(result != null){
            return result.getHostAddress();
        }

        return "localhost";

    }
}
